import Message from './index.vue'

const verticalTop = 16;
const instancesArr = [];

const uuid = (function(){
    let id = 0;
    return function(){
        return id++;
    }
})();

function computedTop(){
    return instancesArr.reduce((prev,cur)=>{
        return prev + cur.$el.offsetHeight + verticalTop;
    },verticalTop)
}

function updateVerticalTop(instance){
    // 找寻当前元素的位置
    let index = 0;
    for(;index<instancesArr.length;index++){
        if(instancesArr[index].id == instance.id) break;
    }
    // 修改后面元素的高度
    let lastTop = instance.vTop;
    instancesArr.splice(index,1);
    for(;index<instancesArr.length;index++){
        // 交换大小
        [instancesArr[index].vTop,lastTop] = [lastTop,instancesArr[index].vTop]
    }
}

export default function install(Vue) {
    Vue.prototype.$message = (options) => {
        //Message.components.TemplateModal = customCom.template;
        const Ctor = Vue.extend(Message);
        const instance = new Ctor({
            propsData:options
        });
        instance.vTop = computedTop();
        // 处理删除逻辑
        instance.id = uuid();
        instance.$once('close',()=>{updateVerticalTop(instance)})
        // 挂载
        instance.$mount(document.createElement('div'));
        instancesArr.push(instance)
    }
}